#include "Gui.h"
#include "SDL.h"
#include "SDL_Draw.h"
#include "SDL_events.h"
#include "pane.h"
#include <list>
#include <boost/shared_ptr.hpp>
Gui::Gui(SDL_Surface *parent){
	std::string type = "pane";
	m_surface = parent;
	m_area.x=0;
	m_area.y=0;
	m_area.h=m_surface->h;
	m_area.w=m_surface->w;
	m_dragable=false;
	m_isClicked=false;
}

void Gui::Draw(){
	if(!m_children.empty())



	
	for (std::list<boost::shared_ptr<widget>>::iterator iter = m_children.begin();iter!=m_children.end();iter++){

    		(*iter)->Draw();

	}
}

void Gui::AddChild(widget* nWidget){
	boost::shared_ptr<widget> n(nWidget);
	m_children.push_back(n);
	nWidget->SetParent(this);
}

std::list<boost::shared_ptr<widget>> Gui::GetChildren(){return m_children;}
widget* Gui::GetParent(){return this;}
void Gui::SetParent(widget *wid){}
SDL_Surface* Gui::GetSurface(){return m_surface;};
SDL_Rect Gui::GetRect(){return m_area;};
void Gui::SetRect(SDL_Rect nRect){m_area = nRect;}
bool Gui::GetClicked(int x,int y){return false;}

void Gui::Proccess(SDL_Event *e){
	if (e->type == SDL_MOUSEBUTTONDOWN){		
		std::list<boost::shared_ptr<widget>> temp;
		std::list<boost::shared_ptr<widget>>::iterator end = m_children.end();
		std::list<boost::shared_ptr<widget>>::iterator iter = m_children.begin();
		while (iter!=end){	
			if((*iter)->IsHovered(e->button.x,e->button.y)){
				temp.clear();
				std::list<boost::shared_ptr<widget>>::iterator iter2 = m_children.begin();
				while (iter2!=end){
					(*iter2)->SetClicked(false);
					if ((*iter2)!=(*iter)){
						temp.push_back((*iter2));
					}
					iter2++;
				}
				(*iter)->SetClicked(true);
				temp.push_front(*iter);
				
			}
			iter++;
		}
		if (temp.empty()) 
			m_children = temp;
	}
	if (e->type == SDL_MOUSEBUTTONUP){
		std::list<boost::shared_ptr<widget>>::iterator end = m_children.end();
		std::list<boost::shared_ptr<widget>>::iterator iter2 = m_children.begin();
		while (iter2!=end){
			(*iter2)->SetClicked(false);
			iter2++;
		}
	}
	if (e->type == SDL_MOUSEMOTION){
		if (!m_children.empty()){			
			std::list<boost::shared_ptr<widget>>::iterator end = m_children.end();
			std::list<boost::shared_ptr<widget>>::iterator iter2 = m_children.begin();			
			while (iter2!=end){			
				if ((*iter2)->GetClicked() && (*iter2)->GetDragable()){
					SDL_Rect temp = (*iter2)->GetRect();
					temp.x+=e->motion.xrel;
					temp.y+=e->motion.yrel;
					(*iter2)->SetRect(temp);									
				}
			iter2++;
			}
		}
	}
}